<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      :inline="true"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="等级编码" prop="infoData.no">
            <el-input v-model="formData.infoData.no" placeholder="请输入等级编码" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="等级名称" prop="infoData.name">
            <el-input v-model="formData.infoData.name" placeholder="请输入等级名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="变更时间">
            <el-date-picker
              v-model="formData.infoData.modifyTime"
              type="date"
              placeholder="选择变更时间"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 机制 -->
      <el-divider content-position="left">机制</el-divider>
      <template v-for="item in formData.mechanismData" :key="item?.id">
        <el-row
          v-if="
            (item && formData.infoData.no === 'HYDJ-20140105-0002' && item.levelId === 2) ||
            (item && formData.infoData.no === 'HYDJ-20140105-0001' && item.levelId === 1)
          "
        >
          <el-col :span="12">
            <el-form-item :label="'时限' + item.id" prop="mechanismData.time">
              <el-input v-model="item.time" v-onlyNumber placeholder="请输入等级名称">
                <template #append>个月</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'金额' + item.id" prop="mechanismData.money">
              <el-input v-model="item.money" v-onlyNumber placeholder="请输入金额">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 特权 -->
      <el-divider content-position="left">特权</el-divider>
      <el-table :data="formData.privilegedData">
        <el-table-column prop="privilegedData.privilegeName" label="特权名称" align="center">
          <template #default="scope"> {{ scope.row.privilegeName }} </template>
        </el-table-column>
        <el-table-column prop="privilegedData.privilegeNum" label="特权次数/月" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.privilegeNum" :precision="0" :min="0" :step="1" />
            <el-switch
              class="ml4"
              v-model="scope.row.havaUnlimited"
              inline-prompt
              active-text="无限制"
              inactive-text="有限制"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column prop="privilegedData.status" label="状态" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              inline-prompt
              active-text="开"
              inactive-text="关"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as MemberLevelApi from '@/api/blind/memberLevel'
import * as MemberMechanismApi from '@/api/blind/memberMechanism'
import * as MemberPrivilegeApi from '@/api/blind/memberPrivilege'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

interface InfoDataType {
  id: any
  no: any
  name: any
  memberNum: any
  modifyTime: any
  status: any
}
interface MechanismDataType {
  id: any
  levelId: any
  money: any
  status: any
  time: any
  createTime: any
}
interface PrivilegedDataType {
  id: any
  levelId: any
  privilegeName: any
  privilegeNum: any
  status: any
}

const infoData = ref<InfoDataType>({
  id: undefined,
  no: undefined,
  name: undefined,
  memberNum: undefined,
  modifyTime: undefined,
  status: undefined
})
const mechanismData = ref<MechanismDataType[]>([
  {
    id: null,
    levelId: null,
    money: null,
    status: null,
    time: null,
    createTime: null
  }
])
const privilegedData = ref<PrivilegedDataType[]>([
  {
    id: 0,
    levelId: 0,
    privilegeName: '',
    privilegeNum: 0,
    status: 0
  }
])
const formData = ref({
  infoData,
  mechanismData,
  privilegedData
})
const formRules = reactive({
  infoData: {
    name: [{ required: true, message: '等级名称不能为空', trigger: 'blur' }]
  }
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value.infoData = await MemberLevelApi.getMemberLevel(id)
      formData.value.mechanismData = (await MemberLevelApi.getMemberMechanismPage(id)).list

      const currLeveId = formData.value.infoData.no === 'HYDJ-20140105-0001' ? 1 : 2
      formData.value.privilegedData = (
        await MemberPrivilegeApi.getMemberPrivilegePage({ levelId: currLeveId })
      ).list.map((item) => {
        item.privilegeNum = Number(item.privilegeNum)
        return item
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    // const data = formData.value as unknown as MemberLevelApi.MemberLevelVO
    if (formType.value === 'create') {
      await MemberLevelApi.createMemberLevel(data.infoData as MemberLevelApi.MemberLevelVO)
      message.success(t('common.createSuccess'))
    } else {
      await MemberLevelApi.updateMemberLevel(data.infoData as MemberLevelApi.MemberLevelVO)
      await MemberMechanismApi.updateMemberMechanism(
        data.mechanismData as MemberMechanismApi.MemberMechanismVO[]
      )
      await MemberPrivilegeApi.updateMemberPrivilege(
        data.privilegedData as MemberPrivilegeApi.MemberPrivilegeVO[]
      )
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
